class BooksController < ApplicationController
  USER_NAME, PASSWORD = "test", "secret" 
  before_filter :authenticate, :except => [:index]
  
  # GET /books
  # GET /books.xml
  def index
    @books = Book.paginate(
                           :page => params[:page], 
                           :per_page => 3,
                           :conditions => ["title like ?", "%#{params[:search]}%"])
    
    case @books.total_entries
      when 0 then render :text => "Aucun livre ne correspond à votre recherche"
      when 1 then redirect_to @books[0]
    end
  end
  
  # GET /books/1
  # GET /books/1.xml
  def show
    @book = Book.find_by_permalink(params[:id])
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @book }
    end
  end
  
  # GET /books/new
  # GET /books/new.xml
  def new
    @book = Book.new
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @book }
    end
  end
  
  # GET /books/1/edit
  def edit
    @book = Book.find_by_permalink(params[:id])
  end
  
  # POST /books
  # POST /books.xml
  def create
    @book = Book.new(params[:book])

    respond_to do |format|
      if @book.save
        flash[:notice] = 'Book was successfully created.'
        format.html { redirect_to(@book) }
        format.xml  { render :xml => @book, :status => :created, :location => @book }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /books/1
  # PUT /books/1.xml
  def update
    @book = Book.find_by_permalink(params[:id])

    respond_to do |format|
      if @book.update_attributes(params[:book]) && @book.author.update_attributes(params[:author])    
        flash[:notice] = 'Book was successfully updated.'
        format.html { redirect_to(@book) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # DELETE /books/1
  # DELETE /books/1.xml
  def destroy
    @book = Book.find_by_permalink(params[:id])
    @book.destroy
    
    respond_to do |format|
      format.html { redirect_to(books_url) }
      format.xml  { head :ok }
    end
  end
  
  @@nb_demandes_basic = 0

  private
  def authenticate
    authenticate_or_request_with_http_basic do |user_name, password| 
      @@nb_demandes_basic += 1
      puts "authenticate_or_request_with_http_basic : " + @@nb_demandes_basic.to_s
      user_name == USER_NAME && password == PASSWORD
    end
  end
end
